#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

#define N 2
#define NUM 1024

void Write(int wid){
    string str = "hello, I am child";
    pid_t pid = getpid();
    int number = 0;

    //创建一个应用缓冲区
    char buffer[NUM];
    while (true){
        //缓冲区当字符串使用，每次清空
        buffer[0] = 0;
        //格式化写入到缓冲区中---字符串处理
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", str.c_str(), pid, number++);

        //发送/写入给父进程
        write(wid, buffer, strlen(buffer));     //注意这里不用+1，只是写入内容，不考虑最后的'\n'

        //cout << number << endl;
        //if(number>=5)
        //    break;

        // 每次休眠1秒
        sleep(1);
    }
}

void Read(int rid){
    //创建一个应用缓冲区
    char buffer[NUM];

    int cnt = 0;
    while (true)
    {
        //sleep(5);
        buffer[0] = 0;
        ssize_t n = read(rid, buffer, sizeof(buffer));
        if(n>0){
            buffer[n] = '\0';
            cout << "father get a message[" << getpid() << "]:" << buffer << endl;
        }
        else if(n==0){
            cout << "father read file done" << endl;
            break;
        }
        else{
            break;
        }
        //cout << n << endl;

        cnt++;
        if (cnt >= 5)
            break;
        //sleep(1);
    }
}

int main(){
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n<0)
        return 1;

    // cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << endl;

    // child-> w, father-> r
    pid_t id = fork();
    if(id < 0)
        return 2;
    if(id == 0){
        //child
        //关闭读端
        close(pipefd[0]);

        //IPC code
        Write(pipefd[1]);

        //关闭写端
        close(pipefd[1]);
        exit(0);
    }
    //father
    //关闭写端
    close(pipefd[1]);

    //IPC code
    Read(pipefd[0]);
    // 关闭读端
    close(pipefd[0]);
    cout << "father close read fd:" << pipefd[0] << endl;

    //父进程回收子进程
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid<0)
        return 3;
    
    cout << "wait child success: " << rid << " exit code: " << ((status>>8)&0xFF) << " exit signal: " << (status&0x7F) << endl;
    sleep(5);
    cout << "father quit" << endl;

    return 0;
}